<script setup>
import {
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue';
import * as echarts from "echarts";
import {Eleme} from "@element-plus/icons-vue";
const props = defineProps({
  rank:{
    required: true
  }
})
const {rank} = toRefs(props);
let chart
const option = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Direct',
      type: 'bar',
      barWidth: '60%',
      data: []
    }
  ]
})

onMounted(() => {
  initChart()
})
watch(() =>rank,(newWords, oldWords) => {
  resetChart(newWords.value)
}, { deep: true })
onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
})
const initChart = () => {
  chart = echarts.init(document.getElementById('wordFrequencyChart'));
  resetChart(rank.value)
}
const resetChart = (rank) => {
  const keys = [];
  const values = [];
  rank.forEach((item) => {
    const [key, value] = Object.entries(item)[0];
    keys.push(key);
    values.push(value);
  })

  option.xAxis[0].data = keys
  option.series[0].data = values
  chart.setOption(option)
}
</script>

<template>
  <div class="card-container">
    <div id="wordFrequencyChart" style="width: 100%; height: 41vh;"></div>
    <div class="button-div">
      <el-button type="primary" color="#EC5832" @click="()=>{chart.resize()}" plain>重置图像</el-button>
    </div>
  </div>

</template>

<style scoped>
.card-container{
  width: 100%;
  height: 50vh;
  display: flex;
  flex-direction: column;
}
.button-div{
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>